<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

interface DepartmentCount {
  department: string
  count: number
}

interface MonthlyCostByDepartment {
  month: string
  total_cost: number
  department: string
}

interface CostByCategory {
  category: string
  total_cost: number
}

interface UsageVsMaintenance {
  device_name: string
  usage_times: number
  maintenance_times: number
  serial_number: string
}

const maintenanceApi = {
  getCountByDepartment: () => {
    return request<DepartmentCount[]>({
      method: 'GET',
      url: '/maintenance/stats/countByDepartment'
    })
  },
  
  getMonthlyCostByDepartment: () => {
    return request<MonthlyCostByDepartment[]>({
      method: 'GET',
      url: '/maintenance/stats/monthlyCostByDepartment'
    })
  },
  
  getCostByDeviceCategory: () => {
    return request<CostByCategory[]>({
      method: 'GET',
      url: '/maintenance/stats/costByDeviceCategory'
    })
  },
  
  getUsageVsMaintenance: () => {
    return request<UsageVsMaintenance[]>({
      method: 'GET',
      url: '/maintenance/stats/usageVsMaintenance'
    })
  }
}

const departmentCountChartRef = ref<HTMLElement | null>(null)
const monthlyCostChartRef = ref<HTMLElement | null>(null)
const categoryCostChartRef = ref<HTMLElement | null>(null)
const usageMaintenanceChartRef = ref<HTMLElement | null>(null)

const getCountByDepartment = async () => {
  try {
    const response = await maintenanceApi.getCountByDepartment()
    initDepartmentCountChart(response.data)
  } catch (error) {
    ElMessage.error('获取部门维护数量失败')
    console.error(error)
  }
}

const getMonthlyCostByDepartment = async () => {
  try {
    const response = await maintenanceApi.getMonthlyCostByDepartment()
    initMonthlyCostChart(response.data)
  } catch (error) {
    ElMessage.error('获取部门月度成本失败')
    console.error(error)
  }
}

const getCostByDeviceCategory = async () => {
  try {
    const response = await maintenanceApi.getCostByDeviceCategory()
    initCategoryCostChart(response.data)
  } catch (error) {
    ElMessage.error('获取设备类型成本失败')
    console.error(error)
  }
}

const getUsageVsMaintenance = async () => {
  try {
    const response = await maintenanceApi.getUsageVsMaintenance()
    initUsageMaintenanceChart(response.data)
  } catch (error) {
    ElMessage.error('获取使用维护频率失败')
    console.error(error)
  }
}

const initDepartmentCountChart = (data: DepartmentCount[]) => {
  if (!departmentCountChartRef.value) return
  
  const chart = echarts.init(departmentCountChartRef.value)
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)',
    title: {
      text: '各部门维护任务数量',
      left: 'center',
      top: '10px',
      textStyle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: '{b}: {c} ({d}%)',
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      textStyle: {
        color: '#7f8c8d'
      }
    },
    series: [
      {
        name: '维护数量',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['40%', '55%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b|{b}}\n{per|{d}%}',
          rich: {
            b: {
              fontSize: 12,
              fontWeight: 'bold',
              color: '#2c3e50'
            },
            per: {
              color: '#7f8c8d',
              backgroundColor: '#f0f8f0',
              padding: [2, 4],
              borderRadius: 2
            }
          }
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 20,
          lineStyle: {
            color: '#bdc3c7'
          }
        },
        data: data.map(item => ({
          value: item.count,
          name: item.department,
          itemStyle: {
            color: getColorByIndex(data.indexOf(item))
          }
        }))
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initMonthlyCostChart = (data: MonthlyCostByDepartment[]) => {
  if (!monthlyCostChartRef.value) return
  
  // 按部门分组数据
  const departments = [...new Set(data.map(item => item.department))]
  const seriesData = departments.map(dept => {
    return {
      name: dept,
      type: 'bar',
      stack: 'total',
      emphasis: {
        focus: 'series'
      },
      data: data.filter(item => item.department === dept).map(item => item.total_cost)
    }
  })
  
  const months = [...new Set(data.map(item => item.month))].sort()
  
  const chart = echarts.init(monthlyCostChartRef.value)
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)',
    title: {
      text: '各部门月度维护成本',
      left: 'center',
      top: '10px',
      textStyle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: (params: any) => {
        let result = `${params[0].axisValue}<br/>`
        params.forEach((item: any) => {
          result += `${item.marker} ${item.seriesName}: ¥${item.value.toLocaleString()}<br/>`
        })
        return result
      },
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    legend: {
      data: departments,
      top: '40px',
      textStyle: {
        color: '#7f8c8d'
      }
    },
    grid: {
      top: '80px',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLine: {
        lineStyle: {
          color: '#bdc3c7'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '成本(元)',
      nameTextStyle: {
        color: '#7f8c8d'
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(189, 195, 199, 0.3)'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        formatter: (value: number) => {
          if (value >= 10000) {
            return `${(value / 10000).toFixed(1)}万`
          }
          return value.toLocaleString()
        }
      }
    },
    series: seriesData.map((series, index) => ({
      ...series,
      itemStyle: {
        color: getColorByIndex(index),
        borderRadius: [4, 4, 0, 0],
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowBlur: 5,
        shadowOffsetY: 3
      }
    }))
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initCategoryCostChart = (data: CostByCategory[]) => {
  if (!categoryCostChartRef.value) return
  
  const chart = echarts.init(categoryCostChartRef.value)
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)',
    title: {
      text: '设备类型维护成本',
      left: 'center',
      top: '10px',
      textStyle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: '{b}: ¥{c}',
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    grid: {
      top: '60px',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.category),
      axisLine: {
        lineStyle: {
          color: '#bdc3c7'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '成本(元)',
      nameTextStyle: {
        color: '#7f8c8d'
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(189, 195, 199, 0.3)'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        formatter: (value: number) => {
          if (value >= 10000) {
            return `${(value / 10000).toFixed(1)}万`
          }
          return value.toLocaleString()
        }
      }
    },
    series: [
      {
        name: '维护成本',
        type: 'bar',
        barWidth: '40%',
        data: data.map(item => item.total_cost),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#16a085' },
            { offset: 1, color: '#1abc9c' }
          ]),
          borderRadius: [4, 4, 0, 0],
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 5,
          shadowOffsetY: 3
        },
        label: {
          show: true,
          position: 'top',
          formatter: (params: any) => {
            return `¥${params.value.toLocaleString()}`
          },
          color: '#16a085',
          fontWeight: 'bold'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initUsageMaintenanceChart = (data: UsageVsMaintenance[]) => {
  if (!usageMaintenanceChartRef.value) return
  
  const chart = echarts.init(usageMaintenanceChartRef.value)
  
  // 按设备名称分组
  const deviceNames = [...new Set(data.map(item => item.device_name))]
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)',
    title: {
      text: '设备使用频率 vs 维护频率',
      left: 'center',
      top: '10px',
      textStyle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: (params: any) => {
        return `
          ${params[0].name}<br/>
          ${params[0].marker} 使用次数: ${params[0].value}<br/>
          ${params[1].marker} 维护次数: ${params[1].value}
        `
      },
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    legend: {
      data: ['使用次数', '维护次数'],
      top: '40px',
      textStyle: {
        color: '#7f8c8d'
      }
    },
    grid: {
      top: '80px',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: deviceNames,
      axisLine: {
        lineStyle: {
          color: '#bdc3c7'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        rotate: 30
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '使用次数',
        nameTextStyle: {
          color: '#3498db'
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(189, 195, 199, 0.3)'
          }
        },
        axisLabel: {
          color: '#7f8c8d'
        }
      },
      {
        type: 'value',
        name: '维护次数',
        nameTextStyle: {
          color: '#e74c3c'
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          color: '#7f8c8d'
        }
      }
    ],
    series: [
      {
        name: '使用次数',
        type: 'bar',
        data: deviceNames.map(name => {
          const items = data.filter(item => item.device_name === name)
          return items.reduce((sum, item) => sum + item.usage_times, 0)
        }),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#3498db' },
            { offset: 1, color: '#2980b9' }
          ]),
          borderRadius: [4, 4, 0, 0],
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 5,
          shadowOffsetY: 3
        },
        label: {
          show: true,
          position: 'top',
          color: '#3498db',
          fontWeight: 'bold'
        }
      },
      {
        name: '维护次数',
        type: 'line',
        yAxisIndex: 1,
        data: deviceNames.map(name => {
          const items = data.filter(item => item.device_name === name)
          return items.reduce((sum, item) => sum + item.maintenance_times, 0)
        }),
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#e74c3c',
          borderWidth: 2,
          borderColor: '#fff'
        },
        lineStyle: {
          width: 4,
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 10,
          shadowOffsetY: 5
        },
        label: {
          show: true,
          position: 'top',
          color: '#e74c3c',
          fontWeight: 'bold'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const getColorByIndex = (index: number): string => {
  const colors = [
    '#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6',
    '#1abc9c', '#d35400', '#34495e', '#16a085', '#c0392b'
  ]
  return colors[index % colors.length]
}

onMounted(() => {
  getCountByDepartment()
  getMonthlyCostByDepartment()
  getCostByDeviceCategory()
  getUsageVsMaintenance()
})
</script>

<template>
  <el-card class="card-box">
    <div class="header">
      <h2>设备维护统计分析</h2>
    </div>
    
    <div class="chart-container">
      <div class="chart-row">
        <div class="chart-item">
          <div ref="departmentCountChartRef" class="chart"></div>
        </div>
        <div class="chart-item">
          <div ref="monthlyCostChartRef" class="chart"></div>
        </div>
      </div>
      <div class="chart-row">
        <div class="chart-item">
          <div ref="categoryCostChartRef" class="chart"></div>
        </div>
        <div class="chart-item">
          <div ref="usageMaintenanceChartRef" class="chart"></div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }
}

.chart-container {
  padding: 1rem;
}

.chart-row {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.chart-item {
  flex: 1;
  height: 400px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
}

.chart {
  width: 100%;
  height: 100%;
}
</style>